package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.UserLocation;
import com.tanhua.manage.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 上传地理位置
     * @param userLocation
     * @param latitude
     * @param longitude
     */
    @Override
    public void save(UserLocation userLocation, Double latitude, Double longitude) {
        //构建查询条件
        Query query = new Query(Criteria.where("userId").is(userLocation.getUserId()));
        //2.判断是否记录过
        userLocation.setUpdated(System.currentTimeMillis());
        // 参数1：经度
        // 参数2：纬度
        // 构建坐标点，GeoJsonPoint 反序列化时会失败
        GeoJsonPoint point = new GeoJsonPoint(longitude,latitude);
        userLocation.setLocation(point);
        if (!mongoTemplate.exists(query,UserLocation.class)){
            //没有记录，添加
            userLocation.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(userLocation);
        }else {
            //有记录，更新地理位置，位置描述
            Update update = new Update();
            update.set("location",point);
            update.set("address",userLocation.getAddress());
            update.set("updated",userLocation.getUpdated());
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }

    }

    /**
     * 搜附近
     * @param loginUserId
     * @param distance
     * @return
     */
    @Override
    public List<UserLocationVo> searchNearBy(Long loginUserId, Long distance) {
        //获取登录者的坐标
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        UserLocation loginUserLocation = mongoTemplate.findOne(query, UserLocation.class);
        System.out.println(loginUserLocation.getLocation());

        List<UserLocationVo> voList = new ArrayList<>();
        //判断 登录用户是否记录坐标
        if (null != loginUserLocation){
            //登录用户的坐标
            GeoJsonPoint location = loginUserLocation.getLocation();
            //以半径distance构建圆circle
            //p1:数值  p2：衡量单位  Metrics.KILOMETERS 千米 公里
            Distance radius = new Distance(distance.doubleValue()/1000, Metrics.KILOMETERS);
            // p1: 圆心所在的坐标，
            // p2: 半径
            Circle circle = new Circle(location,radius);
            //调用monggo查询附近
            //查询要移除自己
            Query nearByQuery = new Query(Criteria.where("userId").ne(loginUserId));
            //范围搜索
            nearByQuery.addCriteria(Criteria.where("location").withinSphere(circle));
            List<UserLocation> userLocations = mongoTemplate.find(nearByQuery, UserLocation.class);
            //把数据转换成UserLocationVo（原因：GeoJsonPoint反序列化时失败，把经纬单独取出来存储）
            voList = UserLocationVo.formatToList(userLocations);
        }

        return voList;
    }

}
